package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ScoreManagement;
import com.ruoyi.system.service.IScoreManagementService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 四级联考成绩合格名单Controller
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@RestController
@RequestMapping("/system/score")
public class ScoreManagementController extends BaseController
{
    @Autowired
    private IScoreManagementService scoreManagementService;

    /**
     * 查询四级联考成绩合格名单列表
     */
    @PreAuthorize("@ss.hasPermi('system:score:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScoreManagement scoreManagement)
    {
        startPage();
        List<ScoreManagement> list = scoreManagementService.selectScoreManagementList(scoreManagement);
        return getDataTable(list);
    }

    /**
     * 导出四级联考成绩合格名单列表
     */
    @PreAuthorize("@ss.hasPermi('system:score:export')")
    @Log(title = "四级联考成绩合格名单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScoreManagement scoreManagement)
    {
        List<ScoreManagement> list = scoreManagementService.selectScoreManagementList(scoreManagement);
        ExcelUtil<ScoreManagement> util = new ExcelUtil<ScoreManagement>(ScoreManagement.class);
        util.exportExcel(response, list, "四级联考成绩合格名单数据");
    }

    /**
     * 获取四级联考成绩合格名单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:score:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scoreManagementService.selectScoreManagementById(id));
    }

    /**
     * 新增四级联考成绩合格名单
     */
    @PreAuthorize("@ss.hasPermi('system:score:add')")
    @Log(title = "四级联考成绩合格名单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScoreManagement scoreManagement)
    {
        return toAjax(scoreManagementService.insertScoreManagement(scoreManagement));
    }

    /**
     * 修改四级联考成绩合格名单
     */
    @PreAuthorize("@ss.hasPermi('system:score:edit')")
    @Log(title = "四级联考成绩合格名单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScoreManagement scoreManagement)
    {
        return toAjax(scoreManagementService.updateScoreManagement(scoreManagement));
    }

    /**
     * 删除四级联考成绩合格名单
     */
    @PreAuthorize("@ss.hasPermi('system:score:remove')")
    @Log(title = "四级联考成绩合格名单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scoreManagementService.deleteScoreManagementByIds(ids));
    }

    /**
     * 获取导入模板
     */
    @PreAuthorize("@ss.hasPermi('system:score:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<ScoreManagement> util = new ExcelUtil<ScoreManagement>(ScoreManagement.class);
        
        // 生成200条模拟数据
        List<ScoreManagement> sampleDataList = generateSampleData(200);
        
        // 导出带有样例数据的模板
        util.exportExcel(response, sampleDataList, "四级联考成绩合格名单样例数据");
    }
    
    /**
     * 生成模拟样例数据
     * 
     * @param count 生成数据条数
     * @return 样例数据列表
     */
    private List<ScoreManagement> generateSampleData(int count) {
        List<ScoreManagement> sampleList = new java.util.ArrayList<>();
        
        // 定义样例数据集合
        String[] names = {"张明", "李红", "王刚", "赵静", "钱伟", "孙芳", "周强", "吴洁", "郑明", "冯雪", 
                           "陈亮", "楚天", "魏新", "蒋辉", "沈建", "韩梅", "杨光", "朱婷", "许军", "马超"};
        String[] nameSuffixes = {"", "华", "明", "平", "安", "志", "伟", "娜", "丽", "芳"};
        String[] schools = {"吉林大学", "东北师范大学", "长春理工大学", "吉林财经大学", "延边大学", 
                          "长春工业大学", "吉林农业大学", "长春中医药大学", "吉林师范大学", "北华大学"};
        String[] units = {"长春市公安局", "吉林市财政局", "松原市教育局", "四平市民政局", "通化市人力资源局", 
                        "白山市农业局", "白城市交通局", "辽源市卫生局", "延边朝鲜族自治州政府", "长春市财政局"};
        String[] positions = {"行政执法岗", "财务分析岗", "教学管理岗", "行政管理岗", "人事管理岗", 
                           "政策研究岗", "规划管理岗", "医疗管理岗", "对外联络岗", "预算管理岗"};
        String[] categories = {"行政执法类", "财经类", "教育类", "管理类", "医疗卫生类", 
                            "工程技术类", "法律类", "公安类", "农业类", "文化传媒类"};
        String[] provinces = {"11", "12", "13", "14", "15", "21", "22", "23", "31", "32"};
        
        java.util.Random random = new java.util.Random();
        
        for (int i = 1; i <= count; i++) {
            ScoreManagement sample = new ScoreManagement();
            
            // 考生基本信息
            sample.setCandidateId("C" + String.format("%05d", i));
            sample.setName(names[random.nextInt(names.length)] + nameSuffixes[random.nextInt(nameSuffixes.length)]);
            sample.setGender(random.nextBoolean() ? "男" : "女");
            
            // 生成身份证号
            String province = provinces[random.nextInt(provinces.length)];
            String city = String.format("%02d", random.nextInt(30) + 1);
            String district = String.format("%02d", random.nextInt(20) + 1);
            int year = 1970 + random.nextInt(30);
            int month = random.nextInt(12) + 1;
            int day = random.nextInt(28) + 1;
            String sequence = String.format("%03d", random.nextInt(999) + 1);
            String checkCode = String.valueOf(random.nextInt(10));
            String idCard = province + city + district + year + String.format("%02d", month) + String.format("%02d", day) + sequence + checkCode;
            sample.setIdCard(idCard);
            
            // 准考证号
            sample.setExamNumber("JL20250" + String.format("%05d", i));
            
            // 成绩信息 - 调整为较低分数范围
            java.math.BigDecimal adminScore = new java.math.BigDecimal(15 + random.nextDouble() * 5).setScale(1, java.math.RoundingMode.HALF_UP);
            java.math.BigDecimal essayScore = new java.math.BigDecimal(12 + random.nextDouble() * 6).setScale(1, java.math.RoundingMode.HALF_UP);
            java.math.BigDecimal profScore = new java.math.BigDecimal(47 + random.nextDouble() * 6).setScale(1, java.math.RoundingMode.HALF_UP);
            
            sample.setAdministrativeAptitudeScore(adminScore);
            sample.setEssayScore(essayScore);
            sample.setProfessionalSubjectScore(profScore);
            
            // 计算总分
            java.math.BigDecimal totalScore = adminScore.add(essayScore).add(profScore).setScale(1, java.math.RoundingMode.HALF_UP);
            sample.setTotalScore(totalScore);
            
            // 报考信息
            sample.setAppliedUnit(units[random.nextInt(units.length)]);
            sample.setAppliedPosition(positions[random.nextInt(positions.length)]);
            sample.setRecruitmentNumber(Long.valueOf(random.nextInt(5) + 1));
            sample.setInterviewRatio("1:" + (random.nextInt(3) + 3)); // 1:3 到 1:5
            sample.setRanking(Long.valueOf(i)); // 初始排名
            
            // 学校和专业信息
            sample.setGraduationSchool(schools[random.nextInt(schools.length)]);
            sample.setPositionCategory(categories[random.nextInt(categories.length)]);
            
            // 专业技能测试
            String hasSkillTest = random.nextBoolean() ? "是" : "否";
            sample.setHasProfessionalSkillTest(hasSkillTest);
            if ("是".equals(hasSkillTest)) {
                java.math.BigDecimal skillScore = new java.math.BigDecimal(48 + random.nextDouble() * 7).setScale(1, java.math.RoundingMode.HALF_UP);
                sample.setProfessionalSkillTestScore(skillScore);
            } else {
                sample.setProfessionalSkillTestScore(java.math.BigDecimal.ZERO);
            }
            
            // 状态信息
            sample.setIsAlternate("N");
            sample.setQualificationReviewResult("通过");
            sample.setIdentityVerificationResult("通过");
            sample.setPhysicalTestResult("通过");
            sample.setFinalResult("通过");
            
            sampleList.add(sample);
        }
        
        // 按总分排序
        sampleList.sort((a, b) -> b.getTotalScore().compareTo(a.getTotalScore()));
        
        // 重新设置排名
        for (int i = 0; i < sampleList.size(); i++) {
            sampleList.get(i).setRanking(Long.valueOf(i + 1));
        }
        
        return sampleList;
    }

    /**
     * 导入四级联考成绩合格名单数据
     */
    @PreAuthorize("@ss.hasPermi('system:score:import')")
    @Log(title = "四级联考成绩合格名单", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<ScoreManagement> util = new ExcelUtil<ScoreManagement>(ScoreManagement.class);
        List<ScoreManagement> scoreList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = scoreManagementService.importScoreData(scoreList, updateSupport, operName);
        return success(message);
    }
    
    /**
     * 生成资格审查名单
     */
    @PreAuthorize("@ss.hasPermi('system:score:edit')")
    @Log(title = "生成资格审查名单", businessType = BusinessType.UPDATE)
    @PostMapping("/generateQualificationList")
    public AjaxResult generateQualificationList()
    {
        String operName = getUsername();
        int count = scoreManagementService.generateQualificationList(operName);
        return success("成功生成资格审查名单，根据面试比例筛选出" + count + "人");
    }

    /**
     * 获取四级联考成绩合格名单统计数据
     */
    @PreAuthorize("@ss.hasPermi('system:score:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        return success(scoreManagementService.getScoreStatistics());
    }
}
